//
//  SelectCountryTableViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/28.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "SelectCountryTableViewController.h"

@interface SelectCountryTableViewController ()

@property (nonatomic, strong) NSMutableArray *areaArray;            // 所有地区
@property (nonatomic, strong) NSMutableArray *titleArray;           // 标题


@end

@implementation SelectCountryTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = JFMainLocalizedString(@"deposit.country");
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"SelectCountryTableViewCell"];
    
}

// 按首字母分组排序数组
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
    
    // 初始化UILocalizedIndexedCollation
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    //初始化一个数组newSectionsArray用来存放最终的数据，我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    for (int i = 0; i < sectionTitlesCount; i++) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
        [dic setObject:[collation sectionTitles][i] forKey:@"sectionTitle"];
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        [dic setObject:array forKey:@"areaArray"];
        //初始化27个空字典加入newSectionsArray
        [newSectionsArray addObject:dic];
    }
    
    
    //将每个名字分到某个section下
    for (CountryEntity *personModel in arr) {
        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
        NSInteger sectionNumber = [collation sectionForObject:personModel collationStringSelector:@selector(countryName)];
        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber][@"areaArray"];
        [sectionNames addObject:personModel];
    }
    
    //对每个section中的数组按照name属性排序
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index][@"areaArray"];
        NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(countryName)];
//        newSectionsArray[index] = sortedPersonArrayForSection;
        [newSectionsArray[index] setObject:sortedPersonArrayForSection forKey:@"areaArray"];
    }
    
    //删除空的数组
    NSMutableArray *finalArr = [NSMutableArray new];
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableDictionary *dic = newSectionsArray[index];
        if (((NSMutableArray *)(dic[@"areaArray"])).count != 0) {
            [finalArr addObject:newSectionsArray[index]];
        }
    }
    
    return finalArr;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.areaArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic = self.areaArray[section];
    NSArray * areaArray = dic[@"areaArray"];
    return [areaArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectCountryTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSArray *array = self.areaArray[indexPath.section][@"areaArray"];
    CountryEntity *entity = array[indexPath.row];
    
//    CountryEntity *entity = self.array[indexPath.row];
    cell.textLabel.text = entity.countryName;
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *string = self.titleArray[section];
    return string;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.titleArray;
}

//响应点击索引时的委托方法
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *array = self.areaArray[indexPath.section][@"areaArray"];
    CountryEntity *entity = array[indexPath.row];
    
    if (self.selectAction) {
        self.selectAction(entity);
    }
    [self.navigationController popViewControllerAnimated:YES];
}



- (NSMutableArray *)areaArray {
    if (!_areaArray) {
        _areaArray = [Currencies().countryList sortedArrayUsingComparator:^NSComparisonResult(CountryEntity * _Nonnull obj1, CountryEntity *  _Nonnull obj2) {
            return [obj1.countryId compare:obj2.countryId];
        }];
        _areaArray = [self sortObjectsAccordingToInitialWith:_areaArray];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"sectionTitle", nil];
        [_areaArray insertObject:dic atIndex:0];
    }
    return _areaArray;
}


- (NSMutableArray *)titleArray {
    if (!_titleArray) {
        _titleArray = [NSMutableArray arrayWithCapacity:10];
        
        [self.areaArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [_titleArray addObject:(NSDictionary *)obj[@"sectionTitle"]];
        }];
    }
    return _titleArray;
}
@end
